package com.fieldchain.ex.fa100.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.custom.dialog.ProgressDialog;
import com.fieldchain.ex.fa100.custom.dialog.PromptDialog;
import com.fieldchain.ex.fa100.inter.SimpleCallBack;
import com.fieldchain.ex.fa100.mvp.base.MyBasePresenter;
import com.fieldchain.ex.fa100.mvp.base.MyBaseView;
import com.fieldchain.ex.fa100.ui.personal.activity.LoginActivity;
import com.fieldchain.ex.fa100.utils.common.StatusBarUtils;
import com.fieldchain.ex.fa100.utils.common.VerticalDisUtils;
import com.fieldchain.ex.fa100.utils.common.VerticalUtils;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.permission.PermissionManager;
import com.fieldchain.ex.fa100.utils.share.ShareManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by byl
 * 2018/09/03 下午：15：32
 */

public abstract class MyBaseActivity<T extends MyBasePresenter, V extends MyBaseView> extends AppCompatActivity implements MyBaseView {
    public Context mContext;
    public T presenter;
    private PromptDialog promptDialog;
    public ProgressDialog progressDialog;
    private int c1 = R.color.bac_root;
    private boolean needReceive = false;
    public boolean needProgress=true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        EventBus.getDefault().register(this);
        initTopBar();
        setContentView(getLayout());
        promptDialog = new PromptDialog(mContext);
        progressDialog = new ProgressDialog(mContext);
        needReceive = true;
        initPresenter();
        findView();
        setValue();
    }


    public abstract void findView();

    public abstract void setValue();

    public abstract int getLayout();

    private void initPresenter() {
        Class c = getClass();
        Type types = c.getGenericSuperclass();
        if (types.toString().contains("<")) {
            Type[] actualTypeArguments = ((ParameterizedType) types).getActualTypeArguments();
            Class<T> tClass = (Class<T>) actualTypeArguments[0];
            try {
                presenter = tClass.newInstance();
                presenter.attachView((V) this, mContext);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpRequest.getInstance().clearAll();
        needReceive = false;
        if (promptDialog != null) {
            promptDialog.dismiss();
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        needReceive=true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        InputMethodManager();

        EventBus.getDefault().unregister(this);
        if (presenter != null) {
            presenter.detachView();
        }

        mContext = null;
        presenter = null;
        PermissionManager.getInstance().clear();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionManager.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(BaseEvent event) {
        int type = event.getType();
        if(needReceive) {
            if (type == 1) {
                if(needProgress)
                progressDialog.show();
            } else if (type == 2) {
                if(needProgress)
                progressDialog.dismiss();
            } else if (type == 403) {
                loginShow();
            }else if(type==3){
                timerStop();
            }
        }
    }
    public void timerStop(){
        VerticalDisUtils.getInstance().stop();
        VerticalUtils.getInstance().stop();
    }

    public void initTopBar() {
        c1 = initSimpleTop() == -1 ? c1 : initSimpleTop();
        StatusBarUtils.getInstance().setWindowStatusBarColor((Activity) mContext, c1);
    }

    public int initSimpleTop() {
        return -1;
    }


    public void loginShow() {
        Log.e("login","loginShow"+getClass().getSimpleName());
        if (promptDialog.isShowing()) {
            promptDialog.cancel();
        }
        String msg;
        msg = "登录过期,请重新登录";
        if (ShareManager.getInstance().getUser() == null) {
            msg = "跳转登录注册页面";
        }
        promptDialog.show();
        promptDialog.setContent(msg);
        promptDialog.setRight("去登录");
        promptDialog.setListener(new SimpleCallBack() {
            @Override
            public void sure() {
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            }
        });

    }


    /**
     * InputMethodManager内存泄露处理
     */
    private void InputMethodManager() {
//        if (mContext == null) return;
//        int count = 0;
//        while (true) {
//            //给个5次机会 省得无限循环
//            count++;
//            if (count == 5) return;
//            try {
//                InputMethodManager localInputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (localInputMethodManager != null) {
//                    Method localMethod = InputMethodManager.class.getMethod("windowDismissed", new Class[]{IBinder.class});
//                    if (localMethod != null) {
//                        localMethod.invoke(localInputMethodManager, new Object[]{((Activity) mContext).getWindow().getDecorView().getWindowToken()});
//                    }
//                    Field mLastSrvView = InputMethodManager.class.getDeclaredField("mLastSrvView");
//                    if (mLastSrvView != null) {
//                        mLastSrvView.setAccessible(true);
//                        mLastSrvView.set(localInputMethodManager, null);
//                        return;
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }
}
